//
//  PlayBackViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/3/18.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "PlayBackViewController.h"
#import <IOTCamera/Monitor.h>
#import "MyCamera.h"
#import <sys/time.h>
#import <IOTCamera/AVIOCTRLDEFs.h>

#import <IOTCamera/AVFRAMEINFO.h>
#import <IOTCamera/ImageBuffInfo.h>
extern unsigned int _getTickCountCamPlaB() {
    
    struct timeval tv;
    
    if (gettimeofday(&tv, NULL) != 0)
        return 0;
    
    return (unsigned int)(tv.tv_sec * 1000 + tv.tv_usec / 1000);
}

#define DEF_WAIT4STOPSHOW_TIME	250

@interface PlayBackViewController ()<MyCameraDelegate,MonitorTouchDelegate>{
    
    NSInteger playbackChannelIndex;

    NSTimer *tmrRecvPlayback;
    bool isPaused;
    bool isOpened;
    NSTimer *recordingTimer;

}
@property (weak, nonatomic) IBOutlet Monitor *playView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *videoInfoLabel;
@property (weak, nonatomic) IBOutlet UILabel *frameInfoLabel;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *playButton;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *pauseButton;


@property (weak, nonatomic) IBOutlet UILabel *eventTime;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;

@property (nonatomic, assign) BOOL bStopShowCompletedLock;

@property (nonatomic, assign) unsigned short mCodecId;

@property CVPixelBufferPoolRef mPixelBufferPool;
@property CVPixelBufferRef mPixelBuffer;
@property (nonatomic, assign) CGSize mSizePixelBuffer;
@end

@implementation PlayBackViewController
@synthesize bStopShowCompletedLock;
@synthesize mCodecId;
@synthesize glView;
@synthesize mPixelBufferPool;
@synthesize mPixelBuffer;
@synthesize mSizePixelBuffer;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNavigationStyle];
    playbackChannelIndex = -1;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidBecomeActive:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];

}
- (void)viewDidUnload {
    
    if (tmrRecvPlayback != nil) {
        
        [tmrRecvPlayback invalidate];
        tmrRecvPlayback = nil;
    }
    
    self.camera = nil;
    self.playButton = nil;
    self.pauseButton = nil;
    self.videoInfoLabel = nil;
    self.frameInfoLabel = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UIApplicationWillResignActiveNotification];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UIApplicationDidBecomeActiveNotification];
    
    [super viewDidUnload];
}


- (void)viewDidAppear:(BOOL)animated {
    
    if (self.camera != nil)
        self.camera.delegate2 = self;
    
    [self play:nil];
    
    NSString *evtName;
    NSString *evtTime;
    
    evtName = [Event getEventTypeName:self.event.eventType];
    
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:self.event.eventTime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    evtTime = [dateFormatter stringFromDate:date];
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@", evtName];
    self.eventTime.text = [NSString stringWithFormat:@"%@",evtTime];
    [super viewDidAppear:animated];
    
    
    [self.playView attachCamera:self.camera];
    
    [self removeGLView:TRUE];

    if( glView == nil ) {
        glView = [[CameraShowGLView alloc] initWithFrame:self.playView.frame];
        [glView setMinimumGestureLength:100 MaximumVariance:50];
        glView.delegate = self;
        [glView attachCamera:self.camera];
    }
    else {
        [self.glView destroyFramebuffer];
        self.glView.frame = self.playView.frame;
    }
  
    
    if( self.mCodecId == MEDIA_CODEC_VIDEO_MJPEG ) {
        [self.playView bringSubviewToFront:self.glView/*self.glView*/];
    }
    else {
        [self.playView bringSubviewToFront:/*monitorPortrait*/self.glView];
    }

    
    

}

- (void)removeGLView :(BOOL)toPortrait
{
    if( self.glView ) {
        BOOL bRemoved = FALSE;
        if(toPortrait) {
            for (UIView *subView in self.playView.subviews) {
                
                if ([subView isKindOfClass:[CameraShowGLView class]]) {
                    
                    [subView removeFromSuperview];
                    NSLog( @"glView has been removed from scrollViewLandscape <OK>" );
                    bRemoved = TRUE;
                    break;
                }
            }
            if( !bRemoved ) {
                for (UIView *subView in self.playView.subviews) {
                    
                    if ([subView isKindOfClass:[CameraShowGLView class]]) {
                        
                        [subView removeFromSuperview];
                        NSLog( @"glView has been removed from scrollViewPortrait <OK>" );
                        //bRemoved = TRUE;  //vic seem no need???
                        break;
                    }
                }
            }
        }
        else {
            for (UIView *subView in self.playView.subviews) {
                
                if ([subView isKindOfClass:[CameraShowGLView class]]) {
                    
                    [subView removeFromSuperview];
                    NSLog( @"glView has been removed from scrollViewPortrait <OK>" );
                    bRemoved = TRUE;
                    break;
                }
            }
            if( !bRemoved ) {
                for (UIView *subView in self.playView.subviews) {
                    
                    if ([subView isKindOfClass:[CameraShowGLView class]]) {
                        
                        [subView removeFromSuperview];
                        NSLog( @"glView has been removed from scrollViewLandscape <OK>" );
                        //bRemoved = TRUE;      //vic seem no need???
                        break;
                    }
                }
            }
        }
    }
}

- (void)dealloc
{
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [tmrRecvPlayback invalidate];
    [super viewWillDisappear:animated];
    
    self.camera.delegate2 = nil;
}

-(void)onLeftButtonClick:(id)sender{
    
    [self.playView deattachCamera];

    if (playbackChannelIndex > 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_STOP;
        req->stTimeDay = [Event getTimeDay:self.event.eventTime];
        req->Param = self.event.eventType;
        
        [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
        
        [self.camera stopSoundToPhone:playbackChannelIndex];
        [self.camera stopShow:playbackChannelIndex];
        [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
        [self.camera stop:playbackChannelIndex];

        
        
        free(req);      
        
    }
    
    [self.camera clearRemoteNotifications];
    

    [self.navigationController popViewControllerAnimated:YES];
}


- (void)cameraStopShowCompleted:(NSNotification *)notification
{
    self.bStopShowCompletedLock = TRUE;
}
- (void)waitStopShowCompleted:(unsigned int)uTimeOutInMs
{
    unsigned int uStart = _getTickCountCamPlaB();
    while( self.bStopShowCompletedLock == FALSE ) {
        usleep(1000);
        unsigned int now = _getTickCountCamPlaB();
        if( now - uStart >= uTimeOutInMs ) {
            NSLog( @"CameraPlaybackController - waitStopShowCompleted !!!TIMEOUT!!!" );
            break;
        }
    }
    
}


- (UIImage *) getUIImage:(char *)buff Width:(NSInteger)width Height:(NSInteger)height {
    
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buff, width * height * 3, NULL);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = CGImageCreate(width, height, 8, 24, width * 3, colorSpace, kCGBitmapByteOrderDefault, provider, NULL, true,  kCGRenderingIntentDefault);
    
    
    UIImage *img = [UIImage imageWithCGImage:imgRef];
    
    
    if (imgRef != nil) {
        CGImageRelease(imgRef);
        imgRef = nil;
    }
    
    if (colorSpace != nil) {
        CGColorSpaceRelease(colorSpace);
        colorSpace = nil;
    }
    
    if (provider != nil) {
        CGDataProviderRelease(provider);
        provider = nil;
    }
    
    return [img copy];
}

- (NSString *)intToStringTime:(NSUInteger)sec {
    NSString *str = @"";
    
    NSUInteger m = sec / 60;
    NSUInteger s = sec % 60;
    
    if (m < 10 && s < 10) {
        str = [NSString stringWithFormat:@"0%ld:0%ld", (unsigned long)m, (unsigned long)s];
        
    }
    else if (m < 10 && s >= 10) {
        str = [NSString stringWithFormat:@"0%ld:%ld", (unsigned long)m, (unsigned long)s];
    }
    else if (m >= 10 && s < 10) {
        str = [NSString stringWithFormat:@"%ld:0%ld", (unsigned long)m, (unsigned long)s];
    }
    else {
        str = [NSString stringWithFormat:@"%ld:%ld", (unsigned long)m, (unsigned long)s];
    }
    
    
    return str;
}



- (void)startRecordingTimer {
    // status
    [recordingTimer setFireDate:[NSDate distantPast]];
}

- (void)stopRecordingTimer {
    // status
    [recordingTimer setFireDate:[NSDate distantFuture]];
}

- (void)setNavigationStyle{
    
    [self setNavigationTitle:@"录像回放" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];

    
}

- (void)recalcMonitorRect:(CGSize)videoframe
{

    
    if( self.glView ) {
        self.glView.parentFrame = CGRectMake(0, 0, self.playView.frame.size.width, self.playView.frame.size.height);
    
    }
}








- (void)reportCodecId:(NSValue*)pointer
{
    unsigned short *pnCodecId = (unsigned short *)[pointer pointerValue];
    
    self.mCodecId = *pnCodecId;
    
    if( self.mCodecId == MEDIA_CODEC_VIDEO_MJPEG ) {
        
        
    }
    else {
        
        [self.playView bringSubviewToFront:/*monitorLandscape*/self.glView];
    }
}


#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size
{
    if (camera_ == self.camera && type == IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL_RESP) {
        
        SMsgAVIoctrlPlayRecordResp1 *resp = (SMsgAVIoctrlPlayRecordResp1 *) data;
        
        switch (resp->command) {
                
            case AVIOCTRL_RECORD_PLAY_START:
            {
                if (isOpened) {
                    
                    if (resp->result > 0 && resp->result <= 32) {
                        
                        playbackChannelIndex = resp->result;
                        
#ifdef LIB_140210
                        [self.camera start4EventPlayback:playbackChannelIndex];
                        [self.camera startShow:playbackChannelIndex ScreenObject:self];
#else
                        [camera start:playbackChannelIndex];
                        [camera startShow:playbackChannelIndex];
#endif
                        [self.camera startSoundToPhone:playbackChannelIndex];
                        
                        isPaused = false;
                    }
                }
                
                NSUInteger seekTimeUsec = 0;
                seekTimeUsec = resp->reserved_;
                NSLog(@"seekTimeUsec=%lu", (unsigned long)seekTimeUsec);
                
                
                break;
            }
            case AVIOCTRL_RECORD_PLAY_PAUSE:
            {
                /*
                 isPaused = !isPaused;
                 
                 if (isPaused)
                 [self showPlayButton];
                 else
                 [self showPauseButton];
                 */
                
                break;
            }
            case AVIOCTRL_RECORD_PLAY_STOP:
            {
                [self.camera stopSoundToPhone:playbackChannelIndex];
                [self.camera stopShow:playbackChannelIndex];
                [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                [self.camera stop:playbackChannelIndex];
                
                isPaused = false;
                
             //   [self showPlayButton];
                
                playbackChannelIndex = -1;
                
                break;
            }
                
            case AVIOCTRL_RECORD_PLAY_END:
            {
                [self.camera stopSoundToPhone:playbackChannelIndex];
                [self.camera stopShow:playbackChannelIndex];
                [self waitStopShowCompleted:DEF_WAIT4STOPSHOW_TIME];
                [self.camera stop:playbackChannelIndex];
                
                SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
                memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
                
                req->channel = 0;
                req->command = AVIOCTRL_RECORD_PLAY_STOP;
                req->stTimeDay = [Event getTimeDay:self.event.eventTime];
                req->Param = self.event.eventType;
                
                [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
                
                free(req);
                
                isPaused = false;
                isOpened = false;
                playbackChannelIndex = -1;
                
              //  [self showPlayButton];
                [SVProgressHUD showInfoWithStatus:@"播放完毕"];
                
                
                if (tmrRecvPlayback != nil) {
                    
                    [tmrRecvPlayback invalidate];
                    tmrRecvPlayback = nil;
                }
                
                if (recordingTimer != nil) {
                    
                    [recordingTimer invalidate];
                    recordingTimer = nil;
                }
                
                break;
            }
            default:
                break;                
        }
    }
}

- (void)camera:(MyCamera *)camera_ _didReceiveFrameInfoWithVideoWidth:(NSInteger)videoWidth VideoHeight:(NSInteger)videoHeight VideoFPS:(NSInteger)fps VideoBPS:(NSInteger)videoBps AudioBPS:(NSInteger)audioBps OnlineNm:(NSInteger)onlineNm FrameCount:(unsigned long)frameCount IncompleteFrameCount:(unsigned long)incompleteFrameCount {
    
    if (camera_ == self.camera) {
        
        if( videoWidth > 1920 || videoHeight > 1080 ) {
            NSLog( @"!!!!!!!! ERROR !!!!!!!!" );
            return;
        }
        CGSize maxZoom = CGSizeMake((videoWidth*2.0 > 1920)?1920:videoWidth*2.0, (videoHeight*2.0 > 1080)?1080:videoHeight*2.0);
        if( glView && videoWidth > 0 && videoHeight > 0 ) {
            [self recalcMonitorRect:CGSizeMake(videoWidth, videoHeight)];
            self.glView.maxZoom = maxZoom;
        }

        self.videoInfoLabel.text = [NSString stringWithFormat:@"%ldx%ld / FPS: %ld / BPS: %ld Kbps", (long)videoWidth, (long)videoHeight, (long)fps, (videoBps + audioBps) / 1024];
        self.frameInfoLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Frame ratio: %d / %d", @"Used for display channel information"),  incompleteFrameCount, frameCount];
    }
}

- (void)updateToScreen:(NSValue*)pointer
{
    LPSIMAGEBUFFINFO pScreenBmpStore = (LPSIMAGEBUFFINFO)[pointer pointerValue];
    [self.glView renderVideo:pScreenBmpStore->pixelBuff];
    
}


#pragma mark - UIApplication Delegate
- (void)applicationWillResignActive:(NSNotification *)notification
{
    if (playbackChannelIndex >= 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_PAUSE;
        req->stTimeDay = [Event getTimeDay:self.event.eventTime];
        req->Param = 0;
        
        [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
    }
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    if (playbackChannelIndex >= 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_PAUSE;
        req->stTimeDay = [Event getTimeDay:self.event.eventTime];
        req->Param = 0;
        
        [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
    }
}


- (IBAction)play:(id)sender {
    
    if (playbackChannelIndex < 0) {
        
        isOpened = true;
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_START;
        req->stTimeDay = [Event getTimeDay:self.event.eventTime];
        req->Param = 0;
        
        [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
        
     //   [self showPauseButton];
        
        if (tmrRecvPlayback != nil) {
            
            [tmrRecvPlayback invalidate];
            tmrRecvPlayback = nil;
        }
        
        tmrRecvPlayback = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(showPlaybackNotFoundMsg) userInfo:nil repeats:nil];
        
    }
    else {
        [self pause:nil];
    }
}
- (void)showPlaybackNotFoundMsg {
    
    if (playbackChannelIndex < 0) {
        
        isOpened = false;
     //   [self showPlayButton];
        [SVProgressHUD showErrorWithStatus:@"无法打开这个视频"];

    }
    
    tmrRecvPlayback = nil;
}

- (IBAction)pause:(id)sender {
    
    if (playbackChannelIndex >= 0) {
        
        SMsgAVIoctrlPlayRecord *req = (SMsgAVIoctrlPlayRecord *) malloc(sizeof(SMsgAVIoctrlPlayRecord));
        memset(req, 0, sizeof(SMsgAVIoctrlPlayRecord));
        
        req->channel = 0;
        req->command = AVIOCTRL_RECORD_PLAY_PAUSE;
        req->stTimeDay = [Event getTimeDay:self.event.eventTime];
        req->Param = 0;
        
        [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_RECORD_PLAYCONTROL Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPlayRecord)];
        
        free(req);
    }
    
    
    isPaused = !isPaused;
    
 //   if (isPaused)
    //    [self showPlayButton];
   // else
      //  [self showPauseButton];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
